package cfs.controller;

import java.sql.Date;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import cfs.databean.CFSTransaction;
import cfs.databean.Customer;
import cfs.databean.Fund;
import cfs.databean.FundPriceHistory;
import cfs.formbean.DepositCheckForm;
import cfs.formbean.DepositForm;
import cfs.formbean.TransactionForm;
import cfs.helper.Helper;
import cfs.helper.TransactionTypes;
import cfs.model.CustomerDAO;
import cfs.model.FundDAO;
import cfs.model.FundPriceHistoryDAO;
import cfs.model.Model;
import cfs.model.TransactionDAO;

public class DepositCheckAction extends Action {

	private FormBeanFactory<DepositCheckForm> formBeanFactory = FormBeanFactory
			.getInstance(DepositCheckForm.class);
	private TransactionDAO transactionDAO;
	private CustomerDAO customerDAO;
	private FundDAO fundDAO;
	private FundPriceHistoryDAO fundPriceDAO;

	public DepositCheckAction(Model model) {
		transactionDAO = model.getTransactionDao();
		customerDAO = model.getCustomerDao();
		fundDAO = model.getFundDao();
		fundPriceDAO = model.getFundHistoryDao();
	}

	public String getName() {
		return "depositCheck.do";
	}

	public String perform(HttpServletRequest request) {
		List<String> errors = new ArrayList<String>();
		try {
			
			HashMap<Integer,String> customerBalanceList = new HashMap<Integer,String>();
			int customerIdSelected;
			boolean customerSelected = false;
			//set form attribute
			DepositCheckForm form = formBeanFactory.create(request);
			request.setAttribute("form", form);
                        
                        ArrayList<DepositForm> formListItem = new ArrayList<DepositForm>();
                        
			//Fetching the list of all the customers
						Customer[] customerList = customerDAO.getAll();
						if (customerList == null || customerList.length == 0) {
							errors.add("No customer found");
						}
						else
						{   
                                                    for(int w=0;w<customerList.length;w++){
                                                        DepositForm dForm = new DepositForm();
                                                        dForm.setFirstname(customerList[w].getFirstname());
                                                        dForm.setLastname(customerList[w].getLastname());
                                                        dForm.setUsername(customerList[w].getUsername());
                                                        double result = customerList[w].getAvailablebalance() * 0.01;
                                                        String finalBalance = Helper.formatWith2Decimal(result);
                                                        dForm.setAvailablebalance(finalBalance);
							dForm.setCustomerid(customerList[w].getCustomer_id());
                                                        formListItem.add(dForm);
                                                    }
                                                    request.setAttribute("formListItem", formListItem);
						}
						if (errors.size() > 0){
                                        		request.setAttribute("errors", errors);
							return "DepositCheck.jsp";
                                                }
						
						//first request
                        if (!form.isPresent()) {
                                return "DepositCheck.jsp";
			}
			
			if(request.getParameter("customerIdSelected") !=null){
                                customerSelected = true;
				customerIdSelected = Integer.valueOf(request.getParameter("customerIdSelected"));
                                Customer customer = customerDAO.lookup(customerIdSelected);
				errors.addAll(form.getValidationErrors());
                                if (errors.size() == 0){
					double checkAmount = Double.valueOf(form.getAmount());
            				CFSTransaction transaction = new CFSTransaction();
                            		transaction.setAmount(Helper.double2ToLong(checkAmount));
                                	transaction.setCustomer_id(customerIdSelected);
                                        transaction.setTransaction_type(TransactionTypes.DEPOSIT_CHECK);

            				transaction.setRequest_date(new Date(new java.util.Date().getTime()));
                    			transaction.setStatus(Helper.PENDING_STATUS);

                        		transaction = transactionDAO.create(transaction);
                                	request.setAttribute("msg",
						"Transaction has been successfully added to the queue");
                                        /*
                                        List<CFSTransaction> transList = transactionDAO.getTransactionList(
						customerIdSelected, TransactionTypes.DEPOSIT_CHECK);
                                        List<TransactionForm> formList = new ArrayList<TransactionForm>();
                                        for (CFSTransaction tran : transList) {
                                            if (tran.getFund_id() > 0) {
						Fund fund = fundDAO.lookup(tran.getFund_id());
						FundPriceHistory fundPrice;
						TransactionForm transForm;
						if (tran.getExecute_date() != null) {
							fundPrice = fundPriceDAO.lookup(fund.getFund_id(),
									tran.getExecute_date());
							transForm = new TransactionForm(tran, fund,
									fundPrice.getPrice());
						} else {
							transForm = new TransactionForm(tran, fund);
						}

						formList.add(transForm);
                                            } else {
						TransactionForm transForm = new TransactionForm(tran);
						formList.add(transForm);
                			    }
                                            
                                        }
                                    request.setAttribute("formList", formList);
                                         * 
                                         * 
                                         */
                                    request.removeAttribute("form");				
				}
			}
                        if(request.getParameter("customerIdSelected") ==null){
                            errors.add("Please Select a Customer");
                        }
                        if (errors.size() > 0){
                               request.setAttribute("errors", errors);
                               return "DepositCheck.jsp";
                        }
			return "viewTransaction.do";
		} catch (DAOException e) {
			errors.add(e.getMessage());
			return "DepositCheck.jsp";
		} catch (FormBeanException e) {
			errors.add(e.getMessage());
			return "DepositCheck.jsp";
		}catch (NumberFormatException e){
                    errors.add("Please input only number values");
                    return "DepositCheck.jsp";
                }
	}

}
